package com.summer.data.springboot;

import com.summer.data.rs.datatype.PageInfo;
import com.summer.data.connection.PageInfoHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 345480567@qq.com
 */
@Component
public class AutoPageInterceptor implements HandlerInterceptor {

    // 返回 true 表示拦截判断通过，可以访问后面的接口
    // 返回 false 表示拦截未通过，直接返回结果给前端
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        int pageNo = 1;
        int pageSize = 10;

        try {
            String pageNoStr = get(request, "page-no");
            pageNo = Integer.parseInt(pageNoStr);
        } catch (NumberFormatException e) {
            try {
                String pageNoStr = get(request, "pageNo");
                pageNo = Integer.parseInt(pageNoStr);
            } catch (NumberFormatException ignored) {
            }
        }

        try {
            String pageSizeStr = get(request, "page-size");
            pageSize = Integer.parseInt(pageSizeStr);
        } catch (NumberFormatException e) {
            try {
                String pageSizeStr = get(request, "pageSize");
                pageSize = Integer.parseInt(pageSizeStr);
            } catch (NumberFormatException ignored) {
            }
        }

        PageInfo page = new PageInfo(pageNo, pageSize);
        PageInfoHolder.setPageInfo(page);

        return true;
    }

    private String get(HttpServletRequest req, String paramName) {
        String parameter = req.getParameter(paramName);
        if (parameter == null) {
            parameter = req.getHeader(paramName);
        }
        return parameter;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        PageInfoHolder.setPageInfo(null);
    }

}
